<template>
  <a-modal
    title="添加同住人"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item><a-input v-show="false" v-decorator="['key']" /></a-form-item>
        <a-form-item><a-input v-show="false" v-decorator="['src1']" /></a-form-item>
        <a-form-item><a-input v-show="false" v-decorator="['src2']" /></a-form-item>
        <a-form-item
          label="姓名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="請輸入同住人姓名" v-decorator="['name', {rules: [{required: true, message: '請輸入同住人姓名！'}]}]" />
        </a-form-item>
        <a-form-item
          label="聯係方式"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="請輸入聯係方式" v-decorator="['phone', {rules: [{required: true, message: '請輸入聯係方式！'}]}]" />
        </a-form-item>
        <a-form-item
          label="身份證號"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="請輸入身份證號" v-decorator="['idCard', {rules: [{required: true, message: '請輸入身份證號！'}]}]" />
        </a-form-item>
         <a-form-item
              label="照片"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-row>
                <a-col :span="12" >
                  <a-input v-show="false" v-decorator="['idCardImagesFront', { initialValue: '' }]" />
                  <a-upload
                    :customRequest="customRequest1"
                    :multiple="false"
                    :showUploadList="false"
                    :before-upload="beforeUpload"
                    name="file">
                    <a-button><a-icon type="upload"/>上傳正面照片</a-button>
                  </a-upload>
                  <a-spin :spinning="divLoading1">
                    <div>
                      <img :src="src1" style="max-width: 99%;width:100px">
                    </div>
                  </a-spin>
                </a-col>
                <a-col :span="12">
                  <a-input v-show="false" v-decorator="['idCardImagesBack', { initialValue: '' }]" />
                  <a-upload
                    :customRequest="customRequest2"
                    :multiple="false"
                    :showUploadList="false"
                    :before-upload="beforeUpload"
                    name="file">
                    <a-button><a-icon type="upload"/>上傳反面照片</a-button>
                  </a-upload>
                   <a-spin :spinning="divLoading2">
                    <div>
                      <img :src="src2" style="max-width: 99%;width:100px">
                    </div>
                  </a-spin>
                </a-col>
              </a-row>
            </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { sysFileInfoUpload, sysFileInfoPreview } from '@/api/modular/system/fileManage'
  export default {
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        src1: '',
        divLoading1: false,
        src2: '',
        divLoading2: false
      }
    },
    methods: {
      // 初始化方法
      add (length) {
        this.visible = true
          setTimeout(() => {
          this.form.setFieldsValue(
            {
              key: 'N' + length + 1
            }
          )
        }, 100)
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('只允許上傳圖片!')
        }
        const isLt2M = file.size / 1024 / 1024 < 6
        if (!isLt2M) {
          this.$message.error('圖片大小不允許超過6MB!')
        }
        return isJpgOrPng && isLt2M
      },
       /**
       * 上传文件
       */
      customRequest1 (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        sysFileInfoUpload(formData).then((res) => {
          if (res.code === 200) {
            this.sysFileInfoPreview(res.data, '1')
            this.$nextTick(() => {
                this.form.setFieldsValue({
                  idCardImagesFront: res.data
                })
            })
          } else {
            this.$message.error('上传失败：' + res.msg)
          }
        })
      },
      customRequest2 (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        sysFileInfoUpload(formData).then((res) => {
          if (res.code === 200) {
            this.sysFileInfoPreview(res.data, '2')
            this.$nextTick(() => {
                this.form.setFieldsValue({
                  idCardImagesBack: res.data
                })
            })
          } else {
            this.$message.error('上传失败：' + res.msg)
          }
        })
      },
      /**
       * 获取图片并转为链接
       */
      sysFileInfoPreview (id, type) {
        sysFileInfoPreview({ id: id }).then((res) => {
          this.downloadfile(res, type)
        }).catch((err) => {
          this.$message.error('预览错误：' + err.message)
        })
      },
      /**
       * 转图片类型
       */
      downloadfile (res, type) {
        const blob = new Blob([res])
        if (type === '1') {
          this.src1 = window.URL.createObjectURL(blob)
          this.$nextTick(() => {
                this.form.setFieldsValue({
                  src1: this.src1
                })
            })
        } else {
          this.src2 = window.URL.createObjectURL(blob)
          this.$nextTick(() => {
                this.form.setFieldsValue({
                  src2: this.src2
                })
            })
        }
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            this.confirmLoading = false
            this.$emit('ok', values)
            this.handleCancel()
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.divLoading1 = false
        this.divLoading2 = false
        this.src1 = null
        this.$nextTick(() => {
          this.form.setFieldsValue({
            src1: this.src1
          })
        })
        this.src2 = null
        this.$nextTick(() => {
          this.form.setFieldsValue({
            src2: this.src2
          })
        })
      }
    }
  }
</script>
